package com.yangli.leecode.a;

/**
 * @author ly
 * @description #https://leetcode-cn.com/problems/zigzag-conversion/solution/zzi-xing-bian-huan-by-jyd/
 * @data 2022/4/22
 */
public class ConvertToZ {
    public static void main(String[] args) {
        ConvertToZ convertToZ = new ConvertToZ();
        System.out.println(convertToZ.convertToZ("PAYPALISHIRING", 4));
    }

    public String convertToZ(String s, int numRows) {
        int length = s.length();
        if (length == 1 || numRows == 1) {
            return s;
        }
        StringBuffer[] sb = new StringBuffer[numRows]; //申明每行字符串数组
        for (int i = 0; i < numRows; ++i) {
            sb[i] = new StringBuffer();
        }
        int row = 0;
        int flag = -1;

        for (int i = 0; i < length; ++i) {
            sb[row].append(s.charAt(i));
            if (i % (numRows-1) == 0) {//当为第一行是 row++ 当为最后一行 row--
                flag = - flag;
            }
            row += flag;
        }
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < numRows; ++i) {
            res.append(sb[i]);
        }
        return res.toString();

    }


}
